# -*- coding: utf-8 -*-
from websocket_server import WebsocketServer
import threading
import json

_py = "Comps/WSServer.py"

'''
WebSocket服务端模块
'''


class WSServer:
    def __init__(self, port=None):
        self.port = port
        self.ip = "0.0.0.0"

        self.heart_recv = "t"
        self.heart_send = "t"

        self.io = {}

        self.wss = None
        self.OnConnect = None
        self.OnClose = None
        self.OnRecv = None
        self.OnSend = None

    def open(self):
        if not self.port:
            print("WSS port为空")
            return
        thread = threading.Thread(target=self.__server_open, args=[], daemon=True)
        # thread.setDaemon(True)
        thread.start()

    def setup(self, conf):
        self.ip = conf["ip"]
        self.port = int(conf["port"])
        self.heart_recv = conf["heart_recv"]
        self.heart_send = conf["heart_send"]

    def __server_open(self):
        wsc = self

        def on_connect(io, server):
            try:
                print("WS连接 id:" + str(io["id"]))
                sid = io["id"]
                handler = io["handler"]
                if wsc.OnConnect:
                    wsc.OnConnect(sid, handler)
            except Exception as err:
                print("err : connect 回调处理失败 ：" + str(err))

        def on_close(io, server):
            try:
                print("WS关闭 id:" + str(io["id"]))
                sid = io["id"]
                handler = io["handler"]
                if self.OnClose:
                    self.OnClose(sid, handler)
            except Exception as err:
                print("err : close 回调处理失败 ：" + str(err))

        def on_recv(io, server, msg):
            sid = io["id"]
            handler = io["handler"]
            if msg == self.heart_recv:
                handler.send_message(self.heart_send)
            elif msg.startswith("login="):
                login = msg.split("login=")[1]
                self.io[login] = handler
                print(login, "注册成功，ID=", sid)
            else:
                print("WS收到:" + str(io["id"]) + "," + str(msg))
                try:
                    if self.OnRecv:
                        self.OnRecv(sid, handler, msg)
                except Exception as err:
                    print("err : on_recv 回调处理失败 ：" + str(err))

        try:
            print("系统", "WebSocket启动，ip:" +self.ip+ ",端口号" + str(self.port))
            self.wss = WebsocketServer( self.ip, self.port)
            self.wss.set_fn_new_client(on_connect)
            self.wss.set_fn_client_left(on_close)
            self.wss.set_fn_message_received(on_recv)
            self.wss.run_forever()
        except Exception as err:
            print("err", "WebSocket服务出错, 端口号" + str(self.port), err)

    def send(self, key, msg):
        print("to=" + key + "，发送=" + msg)
        if key in self.io:
            if isinstance(msg, str):
                self.io[key].send_message(msg)
            else:
                self.io[key].send_message(json.dumps(msg))

    # 退出
    def exit(self):
        self.wss.shutdown()
        self.wss.server_close()
